package com.tech.koufu.ui.activity;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.tech.koufu.MyApplication;
import com.tech.koufu.R;
import com.tech.koufu.action.RequestQueueSingleton;
import com.tech.koufu.model.UserGroups;
import com.tech.koufu.tools.KouFuTools;
import com.tech.koufu.tools.SharedConfig;
import com.tech.koufu.tools.Statics;
import com.tech.koufu.ui.activity.login.LoginActivity;
import com.tech.koufu.ui.adapter.TeamChangeAdapter;

import extras.com.handmark.pulltorefresh.library.PullToRefreshBase;
import extras.com.handmark.pulltorefresh.library.PullToRefreshListView;
import extras.com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import extras.com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class TeamChangeActivity extends Activity{
	private static final String TAG = TeamChangeActivity.class.getName();
	private static final int REFRESH_FINISH = 1;
	private PullToRefreshListView mPullToRefreshListView;
	private ListView actualListView;
	private TeamChangeAdapter mAdapter;
	private MyApplication myApp;
	private ImageView img_callback;
	private TextView tv_title;
//	private StringRequest mRequest;
//	private RequestQueue mQueue;
	private ArrayList<UserGroups> ugList = new ArrayList<UserGroups>();
	private Context context;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_teamchange);
		context = getApplicationContext();
		initView();
		getTeamChange();

	}
	
	private void initView(){
//		mQueue = Volley.newRequestQueue(getApplicationContext());
		img_callback = (ImageView)findViewById(R.id.img_callback);
		img_callback.setVisibility(View.VISIBLE);
		img_callback.setOnClickListener(OnClick);
		tv_title = (TextView)findViewById(R.id.tv_title);
		tv_title.setVisibility(View.VISIBLE);
		tv_title.setText("组别切换");
		myApp = (MyApplication)getApplication();
		mPullToRefreshListView = (PullToRefreshListView)findViewById(R.id.lv_stocks);
		actualListView = mPullToRefreshListView.getRefreshableView(); 
        registerForContextMenu(actualListView);
        mAdapter = new TeamChangeAdapter(getApplicationContext());
        actualListView.setAdapter(mAdapter);
        actualListView.setOnItemClickListener(OnItemClick);        
	}
	
	private void initData(){        
        mAdapter.datas = ugList;        
        mAdapter.notifyDataSetChanged();
		mPullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {

			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) { 
				Mode mode = mPullToRefreshListView.getCurrentMode(); 
		        if(mode == Mode.PULL_FROM_START) { 
		        	 refreshData(); 
		        }  
			}
		});  
	}
	
	private void refreshData(){
		ugList.clear();
		mAdapter.notifyDataSetChanged();
		getTeamChange();
        mAdapter.datas = ugList;        
        mAdapter.notifyDataSetChanged();
	}
	
	private OnItemClickListener OnItemClick = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub
			int web_id = mAdapter.datas.get(position-1).web_id;
			myApp.webId = ""+mAdapter.datas.get(position-1).web_id;
			myApp.url = KouFuTools.UrlChoose(web_id);
			myApp.groupId = ""+mAdapter.datas.get(position-1).group_id;
			myApp.setUserid(myApp.groupId + "X" + myApp.digitalid);
			Log.w("TeamChangeTAG", myApp.url + "||" + myApp.getUserid());
			setResult(6,null);
			TeamChangeActivity.this.finish();
		}
	};
	
	private OnClickListener OnClick = new OnClickListener() {
		
		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			TeamChangeActivity.this.finish();
		}
	};
	
	private void getTeamChange(){
		String url = Statics.URL_PHP+"login";
		StringRequest  mRequest = new StringRequest(Method.POST, url, new Response.Listener<String>() {

			@Override
			public void onResponse(String response) {
				 Log.d("TeamChange", response);
				try {
					if(!TextUtils.isEmpty(response)){
//						ugList = new ArrayList<UserGroups>();
						JSONObject obj = new JSONObject(response);
						if(obj.getInt("status") == 0){
							JSONObject dataObj = new JSONObject(obj.getString("data"));
							JSONArray ugArray = new JSONArray(dataObj.getString("groups"));
							for(int i = 0 ; i < ugArray.length() ; i ++){
								UserGroups ug = new UserGroups(ugArray.getJSONObject(i));
								ugList.add(ug);								
							}
//							myApp.mUserGroups  = ugList;
//							mAdapter.datas = ugList;
//							mAdapter.notifyDataSetChanged();
						}else{
							Toast.makeText(getApplicationContext(), obj.getString("error"), Toast.LENGTH_SHORT).show();
						}
					}
					mHandler.sendEmptyMessage(REFRESH_FINISH);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}, new Response.ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				// TODO Auto-generated method stub
				mPullToRefreshListView.onRefreshComplete();
			}
		}){

			@Override
			protected Map<String, String> getParams() throws AuthFailureError {
				Map<String, String> params = new HashMap<String, String>();
				params.put("userid", myApp.getUserName());
				params.put("password", myApp.getUserpwd());
				return params;
			}		
			@Override
			protected Response<String> parseNetworkResponse(
					NetworkResponse response) {
				try { 
					Map<String, String> responseHeaders = response.headers;
					String rawCookies = responseHeaders.get("Set-Cookie"); 
					Log.v("Login~~SessionID===>", "rawCookies="+rawCookies);
					myApp.phpsessid = rawCookies;

					String dataString = new String(response.data, "UTF-8"); 
					return Response.success(dataString,HttpHeaderParser.parseCacheHeaders(response));
				} catch (UnsupportedEncodingException e) {
					return Response.error(new ParseError(e));
				} 
				//				return super.parseNetworkResponse(response);
			}
		};
		mRequest.setTag(TAG);
		RequestQueueSingleton.getInstance(context).addToRequestQueue(mRequest);
	}
	
	private Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case REFRESH_FINISH:
				mPullToRefreshListView.onRefreshComplete();
				initData();
				break;

			default:
				break;
			}
			super.handleMessage(msg);
		}
		
	};

	@Override
	protected void onStop() { 
		super.onStop();
		RequestQueueSingleton.getInstance(context).cancleAllReq(TAG);
	}

	
}
